package com.ff.xyh.common.entity.useraccess;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 后台许可表
 * </p>
 *
 * @author ff
 * @since 2022-10-30
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="AccessPermission对象", description="后台许可表")
public class AccessPermission implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.ID_WORKER_STR)
    private String id;

    @ApiModelProperty(value = "父类权限，根为0")
    private String pid;

    @ApiModelProperty(value = "权限名")
    private String permission;

    @ApiModelProperty(value = "类型(1菜单，2按钮)")
    private Integer type;

    @ApiModelProperty(value = "权限值")
    private String permissionValue;

    @ApiModelProperty(value = "后端接口路径")
    private String path;

    @ApiModelProperty(value = "组件路径")
    private String component;

    @ApiModelProperty(value = "图标")
    private String icon;

    @ApiModelProperty(value = "是否禁用 0启用 1禁用")
    private Integer isDisabled;

    @ApiModelProperty(value = "层级")
    @TableField(exist = false)
    private int level;

    @ApiModelProperty(value = "下级")
    @TableField(exist = false)
    private List<AccessPermission> children;

    @ApiModelProperty(value = "是否选中")
    @TableField(exist = false)
    private boolean isSelected;

    /**
     * 传入列表和父节点 递归将子节点封装到父节点中
     * @param list
     * @param parent
     * @return
     */
    public static AccessPermission getFinalAccessPermissionObject(List<AccessPermission> list, AccessPermission parent) {
        String parentId = parent.getId();
        List<AccessPermission> tempList = new ArrayList<>(); // 内存占用增多 但是递归遍历长度变小 性能增加
        tempList.addAll(list);
        for (AccessPermission accessPermission : list) {
            if (accessPermission.getPid().equals(parentId)) { // pid等于parent的id时
                accessPermission.setLevel(parent.getLevel() + 1);
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<AccessPermission>());
                }
//                list.remove(accessPermission); 由于还为跳出for循环，list处于被占用状态，会触发并发异常 所以使用tempList解决
                tempList.remove(accessPermission);
                parent.getChildren().add(getFinalAccessPermissionObject(tempList, accessPermission));
            }
        }
        return parent;
    }

}
